<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="500px"
    :before-close="() => emit('close')"
    @open="open"
  >
    <div style="margin-bottom: 15px">请输入新密码</div>
    <div>
      <el-input
        v-model="newPwd"
        placeholder="请输入新密码"
        clearable
      ></el-input>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="() => emit('close')">取消</el-button>
        <el-button type="primary" @click="saveResetPwd">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, ref } from 'vue'
import { resetUserPwd } from '@/api/user/index'

const emit = defineEmits(['close'])
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '',
  },
  isAdd: {
    type: Boolean,
    default: false,
  },
  userId: {
    type: Object,
  },
  userName: {
    type: String,
  },
})
const newPwd = ref('')
const title = ref('')

const open = () => {
  newPwd.value = ''
  title.value = `重置【${props.userName}】的登录密码`
}

const saveResetPwd = () => {
  if (!/^.{5,20}$/.test(newPwd.value)) {
    ElMessage.error('用户密码长度必须介于 5 和 20 之间')
    return
  }
  resetUserPwd(props.userId, newPwd.value).then((res) => {
    ElMessage.success('重置成功')
    emit('close')
  })
}
</script>
